#!C:\Python26


import queVars
import webFunctions
import time

import sys

import logging


def mainLoop(*args, **kwargs):

	log = logging.getLogger("Main.WebLoop")

	pluginHandle = {}

	cfgVars = queVars.configuration
	while 1:
		if not queVars.Qout.empty():											# Giant configuration If statement
			temp = queVars.Qout.get()
			if "chMode" in temp:
				pluginHandle = temp["chMode"]["pointer"]

				queVars.Qin.put({"printText" : "Plugin Set to - %s" % (pluginHandle.siteName)})

				cfgVars.clear()

				#print cfgVars
			elif "aName" in temp:
				cfgVars.aList = [temp["aName"]]
				log.info("Set ArtistName")
			elif "listFile" in temp:
				cfgVars.aList = temp["listFile"]
				log.info("Set Artist List File")
			elif "listMode" in temp:
				cfgVars.nSrcMode = temp["listMode"]
				log.info("Set Name Source")
			elif "ovwMode" in temp:
				cfgVars.ovwMode = temp["ovwMode"]
				log.info("Set Overwrite Mode")


			elif "state" in temp:
				if temp["state"] == "Go":
					if pluginHandle != {}:
						plugin = pluginHandle

						#print "'%s', '%s'" % (cfgVars.aName == "False", cfgVars.aList == "False")
						#print "'%s', '%s'" % (cfgVars.aName, cfgVars.aList)
						#print "'%s', '%s'" % (((cfgVars.aName == "") and (plugin.artistNameEN != 0)), ((cfgVars.aList == "") and (plugin.artistListEN != 0)))
						#print "%s" % (not (((cfgVars.aName == "") and (plugin.artistNameEN != 0)) or ((cfgVars.aList != "") and (plugin.artistListEN != 0))))

						print cfgVars.ovwMode
						print plugin.overwriteModes

						if (cfgVars.ovwMode == "") and (plugin.overwriteModes != []):
							log.info("Overwrite mode not configured")
						else:
							if plugin.retrievalHandles > 1:
								print "Retrieval Handles - ", plugin.retrievalHandles
								handle = []
								for x in range(plugin.retrievalHandles):
									handle.append(webFunctions.WebGetRobust())

							elif plugin.retrievalHandles == 1:

								handle = webFunctions.WebGetRobust()
							else:
								raise ValueError
							log.info("Starting... Overwrite Mode : %s" % (cfgVars.ovwMode))
							log.info("ArtistList : '%s'" % (cfgVars.aList))

							plugin.main(cfgVars, handle)
							print "Returned from Plugin"
							del handle
					else:
						log.info("No Plugin Selected")
				if temp["state"] == "Pause":
					queVars.Qstate.put("pause")
				if temp["state"] == "Stop":
					queVars.Qstate.put("stop")

			elif "exit" in temp:
				cfgVars.dump()
				print "WebThread Stopping"
				sys.exit()
				return
			else:
				queVars.Qerr.put({"printError" : "Unrecognised Command %s" % (temp)})



		time.sleep(0.050)
